<template lang="pug">
  StepPage(
    v-if="stepInfoList.length"
    ref="stepPage"
    :hasFooter="false"
    :stepList="stepInfoList"
    :actIndex="stepActIndex"
    @stepper-finished="getStepFinish")
    .step-content(
      :key="curSlotName"
      :slot="curSlotName")
      .info
        .row
          .number 工单号：{{allFormValues.orderCode}}
        .row
          .col-md-10
            ImportantInfo.important-info(
              :infoList="initFlowList"
              :formValues="allFormValues.formValues"
              :columns="infoColumns")
          .col-md-2.status-box
            p.status 状态
            .status-name(v-if="isGetRelation") {{allFormValues.status | infoRender(statusOptions)}}
          .col-md-12
            el-collapse.flow-important-info(v-model="activeName")
              el-collapse-item(
                v-for="(item, index) in importantInfoList"
                :key="index"
                :name="item.stepDefineId")
                template(slot="title")
                  .base-title
                    .weight 【{{item.stepDefineName}}】
                    div
                      span.weight 操作人：
                      span {{item.operatorName}}
                    div
                      span.weight 操作时间：
                      span {{item.updateTime | formatTime($moment)}}
                ImportantInfo(
                  v-if="item.infoList.length"
                  :infoList="item.infoList"
                  :formValues="item.infoValues"
                  :columns="infoColumns")
</template>

<script>
// uniq,
import { keyBy, isArray } from 'lodash'
import StepPage from '@/components/Step/StepPage'
import SmartDialog from '@/components/SmartDialog'
// import ImportantInfo from '@/components/ImportantInfo'
import ImportantInfo from '@/components/ImportantInfo/FlowImportantInfo'
import SmartForm from '@/components/SmartForm'
// import InfoRender from '@/components/InfoRender'
import {renderForm, getDyncRelation, filterInstanceByStatus} from './renderForm'
import {getUserId} from '@/utils/auth'

import {columns as defaultFlowColumns} from '../../config/workFlow'

export default {
  name: 'FlowStep',
  components: {
    StepPage,
    ImportantInfo,
    SmartForm,
    SmartDialog
    // InfoRender
  },
  created () {
    this.getFlowDetail()
    this.getRelation()
  },
  filters: {
    formatTime (time, moment) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },
    infoRender (val, options) {
      const option = options.find(option => option.value === val)
      return option ? option.label : ''
    }
  },
  route: {
    canActivate (transition) {
      console.log(transition)
      transition.next()
    }
  },
  data () {
    return {
      activeName: '0',
      isGetInfoColumns: false,
      statusOptions: [],
      flowInstanceId: this.$route.query.flow,
      inline: true,
      isGetRelation: false,
      curStepInsList: [],
      allFormValues: {}, // 整体流程数据
      stepTransferList: [], // 流转
      startNode: {}, // 开始节点
      /* 表单字段 */
      formLists: [],
      formColumns: {},
      formValues: {},
      curFormValues: {},
      /* 步骤条信息 */
      stepActIndex: 0,
      stepInfoList: [],
      slotName: '',
      /* 重要信息 */
      initFlowList: ['applyOrgName', 'applyUserName', 'applyTime', 'updateTime'],
      importantInfoList: [],
      infoValues: {},
      infoColumns: {}
    }
  },
  computed: {
    curSlotName: {
      get () {
        return this.stepInfoList[this.stepActIndex].name
      },
      set (value) {
        this.slotName = value
      }
    }
  },
  methods: {
    /* stepPage 关闭 */
    getStepFinish (val) {
      console.log('is finish')
      // this.beforeCloseDialog()
    },
    // /* 切换step数据切换 */
    // changeStepsParams ({stepList = [], curStepIndex = 0}) {
    //   this.curSlotName = this.stepInfoList[curStepIndex].name
    //   this.stepActIndex = Number(curStepIndex)
    // },
    /* 重置数据 */
    resetDatas () {
      const curIndex = this.stepActIndex = 0
      this.curSlotName = this.stepInfoList[curIndex].name
    },
    /* 获取节点信息 */
    getFlowDetail () {
      this.$get({
        url: `/workflow/flowInstance/${this.flowInstanceId}`
      }).then(res => {
        if (!res) return
        const {
          stepDefineList, // 当前定义节点列表
          stepInstanceList, // 实例节点列表
          formValues, // 当前节点最新数据
          columns
        } = res
        this.allFormValues = res
        // 当前实例列表
        // 获取当前活动实例节点，需要根据3个条件筛查出节点定义id - 兼容分支的情况
        const {stepIds} = this.returnCurInstanceList(res) // 可能有n个活动实例
        // n个定义节点列表
        const curDefineList = this.returnCurDefineList(stepIds, stepDefineList)
        // 表单信息
        this.formLists = this.renderFormList(curDefineList, stepIds)
        // step
        this.renderStepDatas(stepInstanceList, stepDefineList, stepIds)
        // 重要信息
        const {importantInfoList, infoColumns, infoValues} = this.renderImportantInfo({stepInstanceList, flowValues: formValues, flowColumns: columns})
        this.importantInfoList = importantInfoList
        this.infoColumns = infoColumns
        this.infoValues = infoValues
      })
    },
    /**
     * @desc 返回n个当前操作者实例节点列表, 实例节点id列表， 定义节点id列表
     * @return {iList: []} 当前活动节点对象数组
     * @return {stepIds: []} 所有当前活动节点id数组
    */
    returnCurInstanceList (res) {
      const {stepInstanceList: instance, status: flowStatus} = res
      const actNodeList = flowStatus === 'ACTIVATY' ? instance.filter(ins => {
        const {operatorId, status, stepNature} = ins
        return status === 'ACTIVATY' && operatorId === Number(getUserId()) && stepNature === 'BIZ'
      }) : []
      const stepIds = keyBy(actNodeList.map(list => {
        return {
          prevStepDefineId: list.prevStepDefineId,
          prevStepInstanceId: list.prevStepInstanceId,
          curStepDefineId: list.stepDefineId,
          curStepInstanceId: list.id
        }
      }), 'curStepDefineId')
      this.curStepInsList = keyBy(actNodeList, 'stepDefineId')
      return {
        iList: actNodeList, // 当前活动节点对象数组
        stepIds: stepIds // 所有当前活动节点id数组
      }
    },
    /* 返回n个定义节点列表 */
    returnCurDefineList (nodes = [], dLists = []) {
      const dNodeIds = Object.keys(nodes)
      return dNodeIds.map(node => {
        return keyBy(dLists, 'id')[Number(node)]
      })
    },
    /* 返回n个表单信息 TODO */
    renderFormList (dList, stepIds) {
      this.isGetRelation = true
      return dList.map(list => {
        const {formList, formColumns} = renderForm(list.formFields)
        const {columns} = getDyncRelation({target: this, columns: formColumns})
        return {
          ...list,
          id: list.id,
          formList,
          formColumns: columns,
          formValues: {
            ...stepIds[list.id]
          }
        }
      })
    },
    /* 返回重要信息 TODO */
    renderImportantInfo ({ flowValues = {}, flowColumns = {}, stepInstanceList = [] }) {
      const columnKey = keyBy(flowColumns, 'name')
      const newColumns = {
        ...defaultFlowColumns,
        ...columnKey
      }
      const {columns} = getDyncRelation({target: this, columns: newColumns}, () => {
        this.isGetInfoColumns = true
      })
      // const currentColumnKey = Object.keys(columnKey).sort((a, b) => {
      //   return columnKey[a].sort - columnKey[b].sort
      // })
      const importantInfoList = stepInstanceList.filter(item => {
        return item.status === 'FINISH' && item.stepNature === 'BIZ'
      }).map(item => {
        const infoValues = item.formValues.reduce((obj, item) => {
          obj[item.name] = item.formValue
          return obj
        }, {})
        return {
          ...item,
          infoValues: infoValues,
          infoList: Array.from(new Set(item.formValues.map(form => form.name)))
        }
      })
      this.activeName = importantInfoList[importantInfoList.length - 1].stepDefineId
      return {
        importantInfoList,
        infoColumns: columns,
        infoValues: flowValues
      }
    },
    /**
     * @params {dList} 定义步骤列表
     * @params {iList} 实例列表
     * 渲染进度条数据
     * 不显示功能节点
     * 结束-act-todo
     */
    renderStepDatas (iList, dList, stepIds) {
      let curStepIndex = 0
      const {doneList, actList, todoNode} = filterInstanceByStatus(iList, dList)
      const mixLists = actList.length ? [...doneList, actList, ...todoNode] : [...doneList, ...todoNode]
      const stepList = mixLists.map((list, index) => {
        if (isArray(list) || stepIds[list.id]) curStepIndex = index// 实例中index
        const target = isArray(list) ? list[0] : list
        return {
          index: index,
          isGroup: target.isGroup ? list : [], // 数组的显示组合
          label: target.stepDefineName || target.name,
          name: target.stepDefineId,
          type: target.stepTypeId,
          components: false,
          status: target.status || '',
          content: `${target.stepDefineName || target.name} - ${target.operatorName || ''}`
        }
      })
      // console.log('curStepIndex-', curStepIndex)
      this.stepInfoList = stepList
      if (!todoNode.length) curStepIndex = mixLists.length - 1
      this.changeStepsParams({stepList, curStepIndex})
      return {
        stepList,
        curStepIndex
      }
    },
    /* 切换step数据切换 */
    changeStepsParams ({stepList = [], curStepIndex = 0}) {
      this.curSlotName = this.stepInfoList[curStepIndex].name
      this.stepActIndex = Number(curStepIndex)
    },

    /* 返回流转路径 */
    renderTransferPath (tList = []) {
      const sourceLists = keyBy(tList, 'sourceStepDefineId')
      const sourceNodes = Object.keys(sourceLists).map(keyId => {
        const target = tList.filter(list => list.sourceStepDefineId === Number(keyId)).map(res => {
          return {
            id: res.targetStepDefineId,
            name: res.targetStepDefineName
          }
        })
        return {
          sourceId: Number(keyId),
          sourceName: sourceLists[keyId].sourceStepDefineName,
          target: target,
          transType: sourceLists[keyId].transType
        }
      })
      return sourceNodes
    },
    getRelation () {
      this.isGetRelation = false
      this.$getRelation({
        relations: 'flowInstanceStatus'
      }).then((data) => {
        // Object.keys(this.infoColumns).map(key => {
        //   const relation = this.infoColumns[key].relation
        //   if (data[relation]) {
        //     this.infoColumns[key].options = [...this.infoColumns[key].optionsInit || [], ...data[relation]].map(option => {
        //       const label = option[this.infoColumns[key].labelName || 'label']
        //       return {
        //         value: option.value !== undefined ? option.value : option.id,
        //         label,
        //         ...option
        //       }
        //     })
        //   }
        // })
        this.statusOptions = data.flowInstanceStatus
        this.isGetRelation = true
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="sass" scoped>
.smart-form-dialogwrap
  padding: 10px
.info
  margin: 20px 30px
  background: #fff
  padding: 35px
  .number
    margin: 0 20px
    font-size: 20px
  .important-info
    border: 0
    padding: 20px 70px 0
  .status-box
    padding: 10px
  .status
    float: right
    // margin-top: 40px
  .status-name
    float: right
    color: #48b0f7
    clear: both
    font-size: 20px
.smart-form-box
  h4
    margin: 30px 30px 0
    border-left: 4px solid #ccc
    padding-left: 10px
    box-shadow: 0px 2px 0 rgba(241,241,241,.6)
    background: #fff
  h4:active
    border-color: #47b1f6
  .smart-form-wrap
    @extend .info
    margin: 5px 30px 30px
    padding: 35px 125px
    .form-box
      width: 66%
      margin: 0 auto
    .button-wrap
      position: absoult
      margin: 30px !important
/deep/.flow-important-info
  margin-top: 5px
  border: 1px solid #ddd
  .important-wrap
    border: 0 !important
    color: #626262
  .el-collapse-item__header
    // color: #1f1c1c
    border-bottom: 1px solid #ddd
  .el-collapse-item__content
    padding-bottom: 0
    background-color: #f4f4f4
.base-title
  display: flex
  justify-content: space-around
  text-align: left
  color: #626262
  div
    width: 33.3%
.weight
  font-weight: bolder
</style>
